package com.mutouren.web;

import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.mutouren.common.cache.impl.CacheManager;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.thread.ThreadPoolManager;
//import com.mutouren.modules.org.client.OrgManager;

public class ContextListener implements ServletContextListener {
	
	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());
	
	//private WebApplicationContext webApplicationContext;

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		ServletContext context = arg0.getServletContext();
		
		runLogger.info(String.format("mutouren system destroy, contextPath: %s, applicationId: %s", 
				context.getContextPath(), context.getAttribute("applicationId")));	
		
		close();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext context = arg0.getServletContext();
		context.setAttribute("applicationId", UUID.randomUUID().toString());
		context.setAttribute("ctx", context.getContextPath());
		
		runLogger.info(String.format("mutouren system initialize, contextPath: %s, applicationId: %s", 
				context.getContextPath(), context.getAttribute("applicationId")));

		//webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
		//displayBeans_debug();
		open();
	}
	
//	@SuppressWarnings("unused")
//	private void displayBeans_debug() {
//		for(String alias :  webApplicationContext.getBeanDefinitionNames()) {
//			Object obj = webApplicationContext.getBean(alias);
//			System.out.println(String.format("%s: %s", alias, obj.getClass()));
//		}
//	}
	
	private void open() {	
		try {		
			runLogger.info("mutouren openJob start.");
			
			//OrgManager.init("mtr-ssoca", "http://127.0.0.1:8080/mtr-modules-organization-api");
			
			runLogger.info("mutouren openJob finish.");
		} catch(Throwable t) {
			errorLogger.error("mutouren openJob error.", t);
		}
	}
	
	private void close() {
		try {
			ThreadPoolManager.close();
			CacheManager.close();
			runLogger.info("mutouren closeJob finish");
		} catch(Throwable t) {
			errorLogger.error("mutouren closeJob error.", t);
		}
		
		// 关闭日志
		LogManager.close();		
	}
}
